package com.sunlei.webtest.quickstart.message;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Author: sun
 * @Description: 为消息添加附加属性
 * @Data: create in 21:15 2018/11/21
 * @Modfied by:
 */
public class MessageProducter {
    public static void main(String[] args) throws IOException, TimeoutException {

        /** 1.创建一个connectionFactory 并进行配置*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        /** 2.通过连接工厂创建连接 */
        Connection connection =  connectionFactory.newConnection();
        /** 3.通过connection创建channel*/
        Channel channel = connection.createChannel();
        /** 4.通过channel发送数据
         *  @1 exchange :exchange名称,如果为空默认为"\",此时的规则是找有没有与routingkey同名的队列进行投递
         *  @2 routingkey
         *  The default exchange is implicitly bound to every queue, with a routing key equal to the queue name.
         *  It is not possible to explicitly bind to, or unbind from the default exchange. It also cannot be deleted.
         * */

        /**定义附加属性
         * deliveryMode 1代表非持久化 2代表持久化投递
         * headers() 方法可以出入自定义属性设置,默认传入map结构
         * */

        Map<String,Object> headers = new HashMap<>();
        headers.put("my1","101");
        headers.put("my2","102");
        headers.put("my3","103");
        //建造者模式
        AMQP.BasicProperties properties = new AMQP.BasicProperties()
                .builder().deliveryMode(2)
                .contentEncoding("UTF-8")
                .expiration("10000")
                .headers(headers)
                .build();
        channel.basicPublish("","test",properties,"message test 1".getBytes());
        channel.basicPublish("","test",properties,"message test 2".getBytes());
        channel.basicPublish("","test",properties,"message test 3".getBytes());
        channel.basicPublish("","test",properties,"message test 4".getBytes());
        channel.basicPublish("","test",properties,"message test 5".getBytes());
        channel.basicPublish("","test",properties,"message test 6".getBytes());
        channel.basicPublish("","test",properties,"message test 7".getBytes());
        channel.basicPublish("","test",properties,"message test 8".getBytes());
        channel.basicPublish("","test",properties,"message test 9".getBytes());
        channel.basicPublish("","test",properties,"message test 10".getBytes());
        /** 5.记得记得关闭连接*/
        channel.close();
        connection.close();
    }
}
